package Model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 *
 * @author kiko
 */
public class MessageReceiver extends Thread {
    
    private Socket conection;
    private String message;
    private BufferedReader in;
    private DataOutputStream out;
    private ConsistencyManager consistencyManager;
    
    public MessageReceiver(Socket conection) {
        this.conection = conection;
        try {
            in = new BufferedReader(new InputStreamReader(conection.getInputStream()));
            out = new DataOutputStream(conection.getOutputStream());
        } catch (IOException e) {
            System.out.println("Erro ao tentar instanciar MessageReceiver");
        }
        consistencyManager = new ConsistencyManager(conection);
        consistencyManager.start();
    }
    
    @Override
    public void run() {
        try {
            interpretMessage(in, out);
        } catch (IOException e) {
            System.out.println("Erro ao tentar interpretar mensagem de servidor");
        }
    }
    
    private void interpretMessage(BufferedReader in, DataOutputStream out) throws IOException {
        while (true) {
            message = in.readLine();
            String auxMessage = message.split(":")[0];
            System.out.println("Mensagem " + auxMessage + " recebida de: " + conection.getInetAddress().toString());
            switch (auxMessage) {
                case "FU"://File updated
                    consistencyManager.add(message.split(":")[1]);
                    break;
                case "GET":
                    if (!message.split(":")[1].equals("null")) {
                        out.writeBytes("FFS\n");
                        System.out.println("FILENAME: " + message.split(":")[1]);
                        consistencyManager.sendFile(message.split(":")[1]);
                    }
                    break;
                case "FFS"://File From Server
                    consistencyManager.receiveFile();
                    break;
                case "PING"://Some server checking if I'm alive
                    out.writeBytes("ALV\n");
                    break;
                case "ALV"://Alive
                    break;
                case "PERM"://Permission to modify file
                    BufferedWriter bw = new BufferedWriter(new FileWriter(message.split(":")[1]));
                    bw.write(message.split(":")[2] + "\n");
                    bw.close();
                    break;
            }
        }
    }
}
